module.exports = class extends think.Model {
	get relation() {
		return {
			role: {
				relation: false,
				type: think.Model.HAS_ONE,
				field: 'id,name',
				key: 'role_id',
				fKey: 'id'
			},
			division: {
				relation: false,
				type: think.Model.HAS_ONE,
				field: 'id,name',
				key: 'div_id',
				fKey: 'id'
			},
			hospital: {
				relation: false,
				type: think.Model.HAS_ONE,
				field: 'id,name',
				key: 'hos_id',
				fKey: 'id'
			}
		};
	}

	/**
	 * @author: ares
	 * @date: 2019/4/3 10:03
	 * @description: 新建
	 * @param {object}data
	 * @returns {Promise.<*>}
	 */
	async $create(data) {
		data.id = think.uuid('v1');
		data.password = 'e10adc3949ba59abbe56e057f20f883e';
		data.birthday = think.datetime(data.birthday, 'YYYY-MM-DD');
		data.create_time = think.datetime(+new Date);
		let find = await this.where({account: data.account}).find();
		if (think.isEmpty(find)) {
			find = await this.transaction(async () => {
				// 通过 db 方法让 其它 模型复用当前模型的数据库连接
				const hospitalDivisionLinkModel = this.model('hospital_division_lk').db(this.db()),
					userHospitalDivisionLinkModel = this.model('hos_div_user_lk').db(this.db()),
					//查询hospital_division_lk表获取医院,科室关联id
					hospitalDivisionLink = await hospitalDivisionLinkModel.where({
						hos_id: data.hos_id,
						div_id: data.div_id
					}).find();
				if (think.isEmpty(hospitalDivisionLink)) throw new Error("hospital_division_lk表查询失败");
				//新增或更新hos_div_user_lk表
				await userHospitalDivisionLinkModel.where({user_id: data.id})
					.thenUpdate({hd_id: hospitalDivisionLink.hd_id, user_id: data.id});
				let _find = await this.add(data);
				return _find;
			})
		} else {
			find = null;
		}
		return find;
	}

	/**
	 * @author: ares
	 * @date: 2019/4/3 11:50
	 * @description: 删除
	 * @param {string}id
	 * @returns {Promise.<*>}
	 */
	async $delete(id) {
		let find = await await this.where({id}).find();
		if (think.isEmpty(find)) {
			return null;
		} else {
			let userHospitalDivisionLinkModel = this.model('hos_div_user_lk');
			await userHospitalDivisionLinkModel.where({user_id: id}).delete();
			return await this.setRelation(false).where({id}).delete();
		}
	}

	/**
	 * @author: ares
	 * @date: 2019/4/3 11:29
	 * @description: 更新
	 * @param {object}data
	 * @returns {Promise.<*>}
	 */
	async $update(data) {
		data.birthday = think.datetime(data.birthday, 'YYYY-MM-DD');
		data.update_time = think.datetime(+new Date);
		let find = await this.where({id: data.id}).find();
		if (think.isEmpty(find)) {
			find = null;
		} else {
			find = await this.transaction(async () => {
				// 通过 db 方法让 其它 模型复用当前模型的数据库连接
				const HospitalDivisionLinkModel = this.model('hospital_division_lk').db(this.db()),
					userHospitalDivisionLinkModel = this.model('hos_div_user_lk').db(this.db()),
					//查询hospital_division_lk表获取医院,科室关联id
					hospitalDivisionLink = await HospitalDivisionLinkModel.where({
						hos_id: data.hos_id,
						div_id: data.div_id
					}).find();
				if (think.isEmpty(hospitalDivisionLink)) throw new Error("hospital_division_lk表查询失败");
				//新增或更新hos_div_user_lk表
				await userHospitalDivisionLinkModel.thenUpdate({
					hd_id: hospitalDivisionLink.hd_id,
					user_id: data.id
				}, {user_id: data.id});
				let _find = await this.where({id: data.id}).update(data);
				return _find;
			})
		}
		return find;
	}

	/**
	 * @author: ares
	 * @date: 2019/4/3 11:37
	 * @description: 切换用户启用禁用状态
	 * @param data
	 * @returns {Promise.<*>}
	 */
	async toggleState(data) {
		data.update_time = think.datetime(+new Date);
		return await this.updateInfo(data);
	}

	/**
	 * @author: ares
	 * @date: 2019/4/3 11:39
	 * @description: 重置用户密码
	 * @param {object}data 用户信息
	 * @returns {Promise.<*>}
	 */
	async resetPwd(data) {
		data.update_time = think.datetime(+new Date);
		data.password = 'e10adc3949ba59abbe56e057f20f883e';
		return await this.updateInfo(data);
	}

	/**
	 * @author: ares
	 * @date: 2019/4/10 16:44
	 * @description: 用户修改自己的密码
	 * @param {string}account    用户账户
	 * @param {string}oldPwd
	 * @param {string}newPwd
	 * @returns {Promise.<*>}
	 */
	async modifyPwd(account, oldPwd, newPwd) {
		let find = await await this.where({account}).find(),
			data = {
				account: account,
				password: newPwd
			};
		if (think.isEmpty(find)) return null;
		return await this.where({account: account, password: oldPwd}).update(data);
	}


	/**
	 * @author: ares
	 * @date: 2019/4/9 13:40
	 * @description: 分页查询,可搜索
	 * @param {string}searchKey   关键字
	 * @param {number}currentPage
	 * @param {number}pageSize
	 * @returns {Promise.<*>}
	 */
	async getListByPage(searchKey, currentPage, pageSize) {
		let result = await this.where({'name|account': ['like', '%' + searchKey + '%']})
			.order(['create_time DESC'])
			.page(currentPage, pageSize)
			.countSelect();
		return result;
	}

	/**
	 * @author: ares
	 * @date: 2019/4/9 14:43
	 * @description: 根据id获取信息
	 * @param {string}id
	 * @returns {Promise.<*>}
	 */
	async getById(id) {
		return await this.where({id}).find();
	}

	/**
	 * @author: ares
	 * @date: 2019/4/9 14:47
	 * @description: 根据账号获取用户信息
	 * @param {string}account
	 * @returns {Promise.<*>}
	 */
	async getByAccount(account) {
		return await this.where({account}).find();
	}

	/**
	 * @author: ares
	 * @date: 2019/4/3 10:04
	 * @description: 用户登录时查询用户是否存在
	 * @param {string|number}account  账号
	 * @param {string}password  密码
	 * @returns {Promise.<void>}
	 */
	async getLoginInfo(account, password) {
		return await this.where({account, password}).find();
	}

	/**
	 * @author: ares
	 * @date: 2019/4/10 11:04
	 * @description: 记录登录/登出信息
	 * @param {object}data
	 * @param {boolean}logout   退出登录
	 * @returns {Promise.<*>}
	 */
	async recordLogin(data, logout) {
		let loginInfo = this.model('login_info'),
			result = logout ? await loginInfo.thenUpdate(data, {token: data.token})
				: await loginInfo.thenUpdate(data, {user_id: data.user_id});
		return result;
	}
};
